java实现从http/https链接地址下载文件

您所在的位置:网站首页 java 文件下载接口 java实现从http/https链接地址下载文件

java实现从http/https链接地址下载文件

2023-09-09 16:25| 来源: 网络整理| 查看: 265

需求:

    现在需要从http地址下载文件改到从https地址下载

改造:

代码示例:

TestDownLoadFile.java

import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; /** * @program: demo * @Date: 2021/4/25 16:21 * @Author: Mr.SU * @Description: */ public class TestDownLoadFile { private Logger logger = LoggerFactory.getLogger(TestDownLoadFile.class); /** * @Description: 测试https地址下载文件 * @param: "[urlStr, fileName, savePath]" * @Return: void * @Author: supenghui * @Date: 2021/4/25 16:21 */ public void downLoadFromUrlHttps(String urlStr, String fileName, String savePath) { try { // 创建SSLContext SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManager[] tm = {new MyX509TrustManager()}; // 初始化 sslContext.init(null, tm, new java.security.SecureRandom()); // 获取SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); // url对象 URL url = new URL(urlStr); // 打开连接 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); /* * 这一步的原因: 当访问HTTPS的网址。您可能已经安装了服务器证书到您的JRE的keystore * 但是服务器的名称与证书实际域名不相等。这通常发生在你使用的是非标准网上签发的证书。 * * 解决方法:让JRE相信所有的证书和对系统的域名和证书域名。 * * 如果少了这一步会报错:java.io.IOException: HTTPS hostname wrong: should be */ conn.setHostnameVerifier(new MyX509TrustManager().new TrustAnyHostnameVerifier()); // 设置一些参数 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 设置当前实例使用的SSLSoctetFactory conn.setSSLSocketFactory(ssf); conn.connect(); // 得到输入流 InputStream inputStream = conn.getInputStream(); byte[] getData = readInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdirs(); } //输出流 File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.info("下载成功"); } /** * @Description: 测试http地址下载文件 * @param: "[urlStr, fileName, savePath]" * @Return: void * @Author: supenghui * @Date: 2021/4/25 16:21 */ private void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException { logger.info("下载文件路径url:{}", urlStr); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为10秒 conn.setConnectTimeout(10 * 1000); //防止屏蔽程序抓取而返回403错误 // conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // conn.setRequestProperty("lfwywxqyh_token",toekn); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } logger.info("---------- 文件地址:" + url + " 下载成功"); } /** * @Description: 从输入流中获取字节数组 * @param: "[inputStream]" * @Return: byte[] * @Author: supenghui * @Date: 2021/4/25 16:21 */ private byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } @Test public void testHttpsToFile() { String url = "https://10.129.168.38/opension-front/loadModelFile?path=/picc/opension/fileManager/S424200ZY201910/WF_Contribution/2021/SZ-4200ZY201910-2021-000010ForSeal.pdf"; String fileName = "资金收账通知.pdf"; String savePath = "D:/nfs/20210425/WF_PN_CONTRIBUTION/2021"; downLoadFromUrlHttps(url, fileName, savePath); } }

MyX509TrustManager.java

import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * @program: demo * @Date: 2021/4/25 15:26 * @Author: Mr.SU * @Description: */ public class MyX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } /** * @Description: 校验https网址是否安全 * @param: "" * @Return: * @Author: supenghui * @Date: 2021/4/25 16:21 */ public class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { // 直接返回true:默认所有https请求都是安全的 return true; } } }

author:su1573 鄙人记录生活点滴,学习并分享,请多指教!!! 如需交流,请联系 [email protected],鄙人看到会及时回复



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3